package com.lwp.ctable.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.lwp.ctable.model.CResult;
import com.lwp.ctable.model.Image;
import com.lwp.ctable.model.Timeline;
import com.lwp.ctable.model.User;
import com.lwp.ctable.service.serviceImp.ImageService;
import com.lwp.ctable.service.serviceImp.TimelineService;
import com.lwp.ctable.service.serviceImp.UserService;
import com.lwp.ctable.utils.OssUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author kaka
 * @Date 2021/4/9 12:12
 * @Version 1.0
 * @Location HANGZHOU
 **/
@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private ImageService imageService;
    @Resource
    private OssUtil ossUtil;
    @Resource
    private TimelineService timelineService;
    private final static Logger logger = LoggerFactory.getLogger(UserController.class);
    public UserController() {
    }
    @RequestMapping("/getById")
    @ResponseBody
    public String getUser(){
        return userService.selectByPrimaryKey(2021000001L).toString();
    }
    @SaCheckLogin
    @ResponseBody
    @RequestMapping("/updateById")
    public String updateUser(){
        User user = userService.selectByPrimaryKey(202100000002L);
        user.setUserTel("13551583109");
        userService.updateByPrimaryKey(user);
        return userService.selectByPrimaryKey(202100000002L).toString();
    }
    @RequestMapping("/login")
    public String login(String account, String password, Model model){
        System.out.println("account="+account+";password="+password);
        logger.info("account="+account+";password="+password);
        User user=userService.selectByAccount(account);
        if (user==null){
            System.out.println("账户不存在");
            return "index";
        }
        if (user.getUserPassword().equals(SaSecureUtil.md5BySalt(password, password))){
            if (!StpUtil.isLogin()){
                StpUtil.setLoginId(user.getUserId());
            }
        }
        StpUtil.checkLogin();
        List<Image> imageList=imageService.selectByUserId(user.getUserId());
        List<String> urlList=new ArrayList<>();
        for (Image image:imageList) {
            urlList.add(image.getUrl());
        }
        List<Timeline> timelineList=timelineService.selectByUserId(user.getUserId());
        model.addAttribute("user",user );
        model.addAttribute("timelineList",timelineList );
        model.addAttribute("urlList", ossUtil.getTemperaryUrl(urlList) );
        System.out.println("urlList = " +ossUtil.getTemperaryUrl(urlList).toString());
        return "main";
    }
    @ResponseBody
    @RequestMapping("/userList")
    public Map<String, Object> userList(){
        Map<String, Object> map = new HashMap<>();
        List<User> userList=userService.selectUserList(0,100);
        if (userList==null){
            map.put("code",-1);
            map.put("msg","无数据");
            map.put("count",0);
            map.put("data",null);
        }
        else{
            map.put("code",0);
            map.put("msg","");
            map.put("count",userList.size());
            map.put("data",userList);
        }
        return map;
    }
    @SaCheckLogin
    @RequestMapping("/logout")
    public String logout(){
        if (StpUtil.isLogin()){
            StpUtil.logout();
        }
        return "index";
    }
    @ResponseBody
    @RequestMapping("/kickOut")
    public CResult kickOut(Long userId){
        StpUtil.logoutByLoginId(userId);
        CResult cResult = new CResult();
        cResult.setCode("200");
        cResult.setMsg("踢出成功");
        cResult.setCount(0);
        cResult.setData(null);
        return cResult;
    }
    @SaCheckLogin
    @ResponseBody
    @RequestMapping("/update")
    public CResult update(User user){
        System.out.println("user = " + user.toString());
        CResult cResult = new CResult();
        if (user!=null){
            userService.updateByPrimaryKeySelective(user);
            return cResult;
        }
        return cResult;
    }
    @RequestMapping("/register")
    @Transactional
    public String register(String account, String email , String password,Model model){
        System.out.println("account="+account+";email="+email+";password="+password);
        if (userService.selectByAccount(account)!=null){
            System.out.println("账户已存在");
            return "index";
        }
        User user=new User();
        user.setUserAccount(account);
        user.setUserEamil(email);
        user.setUserPassword(SaSecureUtil.md5BySalt(password, password));
        if (userService.insert(user)<0){
            throw new RuntimeException();
        }
        System.out.println("注册成功");
        if (!StpUtil.isLogin()){
            StpUtil.setLoginId(user.getUserId());
        }
        Timeline timeline = new Timeline();
        timeline.setContent("<p>创建账号</p>");
        timeline.setRemark("test");
        timeline.setUserId(user.getUserId());
        if (timelineService.insert(timeline)<0){
            throw new RuntimeException();
        }
        System.out.println("登陆成功");
        List<Image> imageList=imageService.selectByUserId(user.getUserId());
        List<String> urlList=new ArrayList<>();
        for (Image image:imageList) {
            urlList.add(image.getUrl());
        }
        List<Timeline> timelineList=timelineService.selectByUserId(user.getUserId());
        model.addAttribute("user",user );
        model.addAttribute("timelineList",timelineList );
        model.addAttribute("urlList", ossUtil.getTemperaryUrl(urlList) );
        StpUtil.checkLogin();
        return "main";
    }
    // 全局异常拦截（拦截项目中的NotLoginException异常）
    @ExceptionHandler(NotLoginException.class)
    public CResult handlerNotLoginException(
            NotLoginException nle, HttpServletRequest request, HttpServletResponse response,Model model)
            throws Exception {

        // 打印堆栈，以供调试
        nle.printStackTrace();

        // 判断场景值，定制化异常信息
        String message = "";
        if(nle.getType().equals(NotLoginException.NOT_TOKEN)) {
            message = "未提供token";
        }
        else if(nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
            message = "token无效";
        }
        else if(nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            message = "token已过期";
        }
        else if(nle.getType().equals(NotLoginException.BE_REPLACED)) {
            message = "token已被顶下线";
        }
        else if(nle.getType().equals(NotLoginException.KICK_OUT)) {
            message = "token已被踢下线";
        }
        else {
            message = "当前会话未登录";
        }

        System.out.println(message);
        CResult cResult = new CResult();
        cResult.setCode("-100");
        cResult.setMsg(message);
        cResult.setCount(0);
        cResult.setData(null);
        return cResult;
    }

}
